import { encode } from 'js-base64'
import { showToast } from '@/utils/utils.js'

const getToken = () => {
  const token = uni.getStorageSync('token')
  if (token) {
    return `Basic ${encode(token + ':')}`
  }
  else {
    return token
  }
}

export const request = (url, method, data={}) => {
  return new Promise((resolve) => {
    uni.request({
      url: import.meta.env.VITE_API_URL + url,
      method, data,
      header: {
        Authorization: getToken()
      },
      success(res) {
        if (res.statusCode === 202) {
          showToast(res.data.msg)
        }
        if (res.statusCode === 500) {
          showToast('内部服务器错误')
        }
        if (res.statusCode === 401) {
          showToast('没有访问权限')
          setTimeout(() => {
            uni.navigateTo({ url: '/pages/login-page/login-page' })
          }, 1000);
        }
        resolve(res.data)
      },
      fail() {
        showToast('网络连接异常')
      }
    })
  })
}